package com.wechet.serveice.impl;

import com.lly835.bestpay.enums.BestPayTypeEnum;
import com.lly835.bestpay.model.PayRequest;
import com.lly835.bestpay.model.PayResponse;
import com.lly835.bestpay.model.RefundRequest;
import com.lly835.bestpay.model.RefundResponse;
import com.lly835.bestpay.service.impl.BestPayServiceImpl;
import com.wechet.common.OrderStatus;
import com.wechet.dto.OrderDto;
import com.wechet.exception.SellException;
import com.wechet.serveice.PayService;
import com.wechet.utils.MathUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.weaver.ast.Or;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;

/**
 * Created by sc on 2017/9/24.
 */
@Service
@Slf4j
public class PayServiceImpl implements PayService {
    private static final String ORDER_NAME = "微信点餐订单";

    @Autowired
    private BestPayServiceImpl bestPayService;

    @Autowired
    private orderServiceImpl orderService;

    @Override
    public PayResponse create(OrderDto orderDto) {
        PayRequest payRequest = new PayRequest();
        payRequest.setOpenid(orderDto.getBuyerOpenid());
        payRequest.setOrderAmount(orderDto.getOrderAmount().doubleValue());
        payRequest.setOrderId(orderDto.getOrderId());
        payRequest.setOrderName(ORDER_NAME);
        payRequest.setPayTypeEnum(BestPayTypeEnum.WXPAY_H5);
        PayResponse payResponse = bestPayService.pay(payRequest);
        return payResponse;
    }

    @Override
    public PayResponse notify(String notifyData) {
        //1.验证签名
        //2.支付状态
        //3.支付金额(0.1 0.10)
        //4.支付人(下单人==支付人)
        PayResponse payResponse = bestPayService.asyncNotify(notifyData);
        OrderDto orderDto = orderService.findOne(payResponse.getOrderId());
        if (orderDto == null) {
            log.error("订单不存在");
            throw new SellException(OrderStatus.ORDER_NOT_EXIST);
        }
        if (!MathUtil.equals(payResponse.getOrderAmount(), orderDto.getOrderAmount().doubleValue())) {
            log.error("金额不一致");
            throw new SellException("金额不一致");
        }

        orderService.paid(orderDto);
        return payResponse;
    }

    @Override
    public RefundResponse refund(OrderDto orderDto) {
        RefundRequest refundRequest = new RefundRequest();
        refundRequest.setOrderId(orderDto.getOrderId());
        refundRequest.setPayTypeEnum(BestPayTypeEnum.WXPAY_H5);
        refundRequest.setOrderAmount(orderDto.getOrderAmount().doubleValue());
        RefundResponse refundResponse = bestPayService.refund(refundRequest);
        return refundResponse;
    }

}
